package com.hunliji.monitor.web.filter.auth;

import com.alibaba.fastjson.JSON;
import com.hunliji.common.exception.WarnException;
import com.hunliji.hljsso.client.HljSsoClient;
import com.hunliji.monitor.service.api.UserInfoService;
import com.hunliji.monitor.service.api.model.bo.UserInfoBO;
import com.hunliji.monitor.web.filter.GeneralContext;
import com.hunliji.monitor.share.component.db.DatabaseConnectionsAdapter;
import com.hunliji.monitor.share.model.AdminBO;
import com.hunliji.monitor.share.utils.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 *
 * @author wuchen
 */
@Aspect
@Component
public class AuthAspect {
    private final static Logger log = LoggerFactory.getLogger(AuthAspect.class);
    @Resource
    private UserInfoService userInfoService;

    @Pointcut("@annotation(com.hunliji.monitor.web.filter.auth.NeedAuth)")
    public void cut() {
    }

    @Around("cut()")
    public Object cutCheckUser(ProceedingJoinPoint pjp) throws Throwable {
        String token = SpringContext.getAuth();
        if(StringUtils.isBlank(token)){
            throw new WarnException("未登录");
        }
        AdminBO adminBO = JwtUtil.unsignToken(token);
        if(Objects.isNull(adminBO)){
            throw new WarnException("未登录");
        }
        //匹配userInfo信息
        UserInfoBO userInfoBO = userInfoService.queryByMail(adminBO.getUsername());
        if(Objects.isNull(userInfoBO)){
            throw new WarnException("用户不存在");
        }
        GeneralContext.setAdmin(userInfoBO);
        log.info("打印验证信息:{}", JSON.toJSONString(adminBO));
        return pjp.proceed();
    }

}
